import { Form, Col, Row, Radio, message, Select, Badge, Empty, Input, Card, Image, Pagination, Space, TreeSelect } from 'antd';
import { Link, useRequest ,useModel} from 'umi';
import React, { useState, useRef, useEffect } from 'react';

import { QueryFilter, ProFormText, ProFormRadio, ProFormSelect } from '@ant-design/pro-form';

import { PageLoading } from '@ant-design/pro-layout';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { queryAreaTree } from '@/services/area';
import {
  CalendarOutlined, SearchOutlined,ArrowDownOutlined
} from '@ant-design/icons';

import styles from './style.less'
import slg from '@/assets/img/img/slg.png';
import slg1 from '@/assets/img/img/slg1.png';
import slg2 from '@/assets/img/img/slg2.png';
import list from '@/assets/img/img/list.png';


import listtype1 from '@/assets/img/img/listtype1.png';
import listtype2 from '@/assets/img/img/listtype2.png';

import warn from '@/assets/img/img/warn.png';
import trip from '@/assets/img/img/trip.png';
import alarm from '@/assets/img/img/alarm.png';
import nomal from '@/assets/img/img/nomal.png';


import { deviceRealtimeList,deviceRealtimeCount } from '@/services/device';
import { queryDeviceTypeList } from '@/services/devicetype';
const realtime: React.FC = (props) => {
  const actionRef = useRef<ActionType>();
  const { params } = props.match;



  const [dateSourse, setDateSourse] = useState<API.DeviceItem>();
  const [areaTreeData, setAreaTreeData] = useState<API.TreeNodeItem[]>([]);
  const [searchDate, setSearchDate] = useState();
  const [total, setTotal] = useState<number>(0);
  const [pageSize, setPageSize] = useState<number>(15);
  const [current, setCurrent] = useState<number>(1);
  const [onlineNum, setOnlineNum] = useState<number>(0);
  const [allCount, setAllCount] = useState<number>(0);
  
  const [loading, setLoading] = useState<boolean>(false);
  const [typeEnumValues, setTypeEnumValues] = useState();
  const [areaEnumValues, setAreaEnumValues] = useState({});



  const columns = [
    {
      title: '',
      key: 'running',
      search: false,
      render: (text, record) => (

        <Space size="middle">
          {btnReactNode(record)}
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'deviceTypeName',
 
    }, {
      title: '区域位置',
      valueEnum: areaEnumValues,
      dataIndex: 'areaId',
      render: (text, record) => (
        <Space size="middle">
          {text}{record.devicePosition}
        </Space>
      ),
    },
    {
      title: '名称',
      dataIndex: 'deviceName',
      render: (text, record) => (
        <Space size="middle">
           <Link   to={{pathname:`/detailsV1/${record.deviceTypeId}/${record.deviceId}`}}    >  {text}</Link> 
        </Space>
      ),
    }, {
      title: '品牌',
      dataIndex: 'deviceBrand'
    },
    {
      title: '型号',
      dataIndex: 'deviceModel',
    },

    // {
    //   title: '设备控制',
    //   search: false,
    //   key: 'gatewayID',
    //   render: (text, record) => (
    //     <Space size="middle">
    //       <a>Invite {record.equipmentModel}</a>
    //       <a>Delete</a>
    //     </Space>
    //   ),
    // }

  ];
  const [model, setModel] = useState<string>('1')
  const [sort, setSort] = useState<string>('1')
  function handleSizeChange(e) {
    setModel(e.target.value);
  }

  function handleSortChange(e) {
    setSort(e.target.value);
  }
  async function onShowSizeChange(c, ps) {
    if (!loading) {
      setPageSize(ps);
    }
  }

  async function onChange(c, ps) {
    if (!loading) {
      setCurrent(c);
      // await getTableDate({current:c});
    }
  }

  const { run } = useRequest(() => getTableDate({}), { manual: true });
  useEffect(() => {
    run();
  }, [pageSize, current, searchDate,sort]);
  useEffect(() => {
    
      deviceRealtimeCount(params).then(function(data){
        console.log(data.onlineNum)
         setOnlineNum(data.onlineNum);
        })
   
  }, []);
  
  //轮询
  // useRequest(getTableDate, {
  //   pollingInterval: 1000,
  //   pollingWhenHidden: false,
  // });

  async function getTableDate(pams) {
  
    setLoading(true);
    let tabledate = await deviceRealtimeList(
      {
        current: current,
        pageSize: pageSize,
        sort:sort,
        ...searchDate,
        ...params,
        ...pams

      });
    setDateSourse(tabledate.data);
   
    setTotal(tabledate.total);
    setCurrent(tabledate.current);
    setLoading(false);

  }

  const btnReactNode = function (e) {
    if(e.trip==1||e.alarmLevel=='803'){
      return (<span className={[styles.shebeiStateBtn, styles.offLine].join(' ')}>故障</span>);
    }else if(e.alarm==1||e.alarmLevel=='802'){
      return (<span className={[styles.shebeiStateBtn, styles.alarm].join(' ')}>报警</span>);
    }else if(e.alarmLevel=='801'){
      return (<span className={[styles.shebeiStateBtn, styles.warn].join(' ')}>警告</span>);
    } else {
      return (<span className={styles.shebeiStateBtn}>正常</span>);
    }
  }



  useEffect(() => {
    const setSelectData = async () => {
      let trees = await queryAreaTree();
      let ddata = {};
      if (trees && trees.length > 0) {
        trees.forEach(item => {
          ddata[item.key] = { text: item.title };
          if (item.children != null) {
            item.children.forEach(children => {
              ddata[children.key] = { text: children.title };
            })
          }
        });
      }
      setAreaEnumValues(ddata);
      setAreaTreeData(trees);
      const deviceType = await queryDeviceTypeList();
      let tdata = {};
      if (deviceType && deviceType.length > 0) {
        deviceType.forEach(item => {
          tdata[item.typeId] = { text: item.typeName, img: item.typeImg };
        });
      }
      setTypeEnumValues(tdata);


    };
    setSelectData();
  }, []);


  // const getTypeUrl = (typeId: number) => {
  //   var type = typeEnumValues[typeId];
  //   if (type == null)
  //     return "";
  //   return type.img;
  // }

  const getTypeUrl = (typeId: number) => {
    var url = null;
    switch (typeId) {
      case 1:
        url = slg1;
        break;
      case 3:
        url = slg2;
        break;
     
      default:
        url = slg;
        break;
    }
    return url;
  }

  const getStateUrl = function (e) {
    if(e.trip==1||e.alarmLevel=='803'){
      return (trip);
    }else if(e.alarm==1||e.alarmLevel=='802'){
      return (alarm);
    }else if(e.alarmLevel=='801'){
      return (warn);
    }else {
      return (nomal);
    }
  }


  
  const getRealTimeData = function (data) {
    if(data?.deviceTypeId==2){
      return (<div style={{margin: '10px 0 8px'}} className={styles.flex}>电流： 
      <div className={styles.dataBox}>{data?.online==0||data?.phaseaCurrent==null?"--":data?.phaseaCurrent}<span className={styles.unit}>A</span></div>.
      <div className={styles.dataBox}>{data?.online==0||data?.phasebCurrent==null?"--":data?.phasebCurrent}<span className={styles.unit}>A</span></div>.
      <div  className={styles.dataBox}>{data?.online==0||data?.phasecCurrent==null?"--":data?.phasecCurrent}<span className={styles.unit}>A</span></div></div>);
    }else if(data?.deviceTypeId===1){
      return ( <div style={{margin: '10px 0 8px',justifyContent: 'center'}} className={styles.flex}>运行频率：
      <div className={styles.dataBox}>{data?.online==0||data?.phaseaCurrent==null?"--":data.phaseaCurrent}<span className={styles.unit}>Hz</span></div>
    </div>);
    }else if(data?.deviceTypeId===3){
        return (<div style={{margin: '10px 0 8px',justifyContent: 'center'}} className={styles.flex}>总有功电量：
                <div className={styles.dataBox}>{data?.online==0||data?.totalActiveEnergy==null?"--":data.totalActiveEnergy}<span className={styles.unit}>kw.h</span></div>
              </div>);
    }
    
    // else{
    //   return (<div style={{margin: '10px 0 8px'}} className={styles.flex}>总有功电能： 
    //   <div className={styles.dataBox}>{data?.online==0?"--":data?.phaseaCurrent||"--"}</div>.
    //   <div className={styles.dataBox}>{data?.online==0?"--":data?.phasebCurrent||"--"}</div>.
    //   <div  className={styles.dataBox}>{data?.online==0?"--":data?.phasecCurrent||"--"}</div><span className={styles.unit}>kw-h</span></div>);
    // }
  }
  return (
    <div className={styles.main}>
      {loading ? <div style={{ paddingTop: '240px', position: 'absolute', height: '100%', width: '100%', zIndex: 9999 }}>
        <PageLoading />
      </div> : <></>}
      <Row className={styles.tabletop}>
        <div className={styles.RTL} > 
           <Image src={list} preview={false} /> &nbsp;<span  className={styles.title}>智能设备</span>
        </div>
        <Row className={styles.totalR}>
          <span>总数：{total||0}</span>
          <span>在线：{onlineNum||0}</span>
          <span>离线：{(total||0)-(onlineNum||0)}</span>
        </Row>
      </Row>
      <QueryFilter span={6}  defaultCollapsed   onReset ={()=> {setSearchDate({});  } } className={styles.searchBox} style={{ display: model != '2' ? 'block' : 'none' }} onFinish={async (values: any) => {
       console.log(values)
       setSearchDate(values);
      }}>
         <Form.Item name={"areaId"} label={""} >
          <TreeSelect size={"middle"}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={areaTreeData}
            placeholder="区域"
            treeDefaultExpandAll
          />
        </Form.Item>
        <ProFormSelect name="deviceTypeId" placeholder="类型" valueEnum={typeEnumValues} />
        <ProFormText name="searchValue"  fieldProps={{
                 
                  suffix: <SearchOutlined  />,
                }}  allowClear placeholder="设备位号/名称/型号/品牌" />
      </QueryFilter>
      <Row className={styles.tabletop}>
        <div className={styles.RTL} >
          <span > 运行状态</span>
          <span><Badge color="rgb(39 208 138)" />正常</span>
          <span><Badge color="#f2b566" />警告</span>
          <span><Badge color="#fd6863" />报警</span>
          <span><Badge color="#ccc" />故障</span>
        </div>
        <Radio.Group value={{ model }} onChange={handleSortChange} className={styles.shanxuan} style={{width:'306px'}}>
            <Radio.Button value="1" className={sort == '1' ?  [styles.btnSelected, styles.shanxuanBtn].join(' ') : styles.shanxuanBtn}>默认排序<ArrowDownOutlined /></Radio.Button>
            <Radio.Button value="2" className={sort == '2' ? [styles.btnSelected, styles.shanxuanBtn].join(' ') : styles.shanxuanBtn}>运行状态<ArrowDownOutlined /></Radio.Button>
            <Radio.Button value="3" className={sort == '3' ? [styles.btnSelected, styles.shanxuanBtn].join(' ') : styles.shanxuanBtn}>区域排序<ArrowDownOutlined /></Radio.Button>
          </Radio.Group>
          <Radio.Group value={{ model }} onChange={handleSizeChange} className={styles.shanxuan}>
            <Radio.Button value="1" className={model == '1' ?  [styles.btnSelected, styles.shanxuanBtn].join(' ') : styles.shanxuanBtn}><Image src={listtype1} preview={false} /> 陈列模式</Radio.Button>
            {/* <Radio.Button value="2" className={model == '2' ? styles.btnSelected : ''}><CalendarOutlined />模型模式</Radio.Button> */}
            <Radio.Button value="3" className={model == '3' ? [styles.btnSelected, styles.shanxuanBtn].join(' ') : styles.shanxuanBtn}><Image src={listtype2} preview={false} /> 表格模式</Radio.Button>
          </Radio.Group>
        </Row>
    
      <ProTable<API.DeviceItem> style={{ display: model == '3' ? 'block' : 'none' }}
        headerTitle=""
        actionRef={actionRef}
        rowKey="deviceId"
        toolBarRender={false}
        search={false}
        dataSource={dateSourse}
        columns={columns}
        pagination={false}
      />
      <div style={{ display: model == '1' ? 'block' : 'none' }}>
        <Row gutter={[10,12]}>
          {total > 0 && typeEnumValues != undefined ? dateSourse.map((data, index)  => 
          <Col className={styles.deviceBox} key={index} >
            <Link   to={{pathname:`/monitoring/details/${data.deviceTypeId}/${data.deviceId}`}}    >
              <Card key={data.deviceId} style={{ height: '100%' }} >
                <Row className={styles.tabletop}>
                  <div className={styles.title1} key={data.deviceNo}>
                    {data.areaName}
                  </div>
                  {/* {btnReactNode(data)} */}
                  {data.online==1? <span><Badge color="rgb(39 208 138)" />在线</span>
                  :   <span><Badge color="#ccc" />离线</span>
                  }
                </Row>
                {getRealTimeData(data)}
              
                <div className={styles.flex}>
                  <div       className={styles.deviceImgBox}>
                  <Image
                    width={65}
                    height={65}
                    src={getTypeUrl(data.deviceTypeId)}
                    // fallback={getTypeErrUrl(data.deviceTypeId)}
                    preview={false}
                  />
                  <Image
                    src={getStateUrl(data)}
                    preview={false}
                  />
                  </div>
                  <div className={styles.rightInfo}>
                    <p>类型：{typeEnumValues[data.deviceTypeId]?.text}</p>
                    <p>位号：{data.deviceNo}</p>
                    <p>名称：{data.deviceName}</p>
                  </div>
                </div>
              </Card>
            </Link>
          </Col>
          ) : <div className={styles.empty}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></div>}
        </Row>
      </div>
      <Row className={styles.pagination} style={{ display: model != '2' ? 'flex' : 'none' }} >
        <Pagination
          total={total}
          showTotal={total => `共 ${total} 项`}
          defaultPageSize={pageSize}
          defaultCurrent={current}
          current={current}
          hideOnSinglePage={true}
          onShowSizeChange={onShowSizeChange}
          onChange={onChange}
        />
      </Row>
      {/* <div className={styles.moxingBox} style={{ display: model == '2' ? 'block' : 'none' }}>
        <Image width={'100%'} src={moxing} preview={false} />
      </div> */}
    </div>

  );
};

export default realtime;